package com.itheima.service;

import com.itheima.common.R;
import com.itheima.mapper.ShoppingCartMapper;
import com.itheima.pojo.ShoppingCart;
import com.itheima.pojo.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Envy
 */
@Service
public class ShoppingCartService {
    @Resource
    private ShoppingCartMapper shoppingCartMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 加入购物车
     */
    public R<ShoppingCart> addShoppingCart(ShoppingCart shoppingCart) {
        //同一个用户在短时间内快速点击
        //要求只有当第一个请求可以通过，其他请求被阻止
        //分布式锁的核心
        Boolean result = redisTemplate.opsForValue().setIfAbsent("lock" + shoppingCart.getId(), System.currentTimeMillis(), 1, TimeUnit.SECONDS);
        if (!result) {
            System.out.println("上锁，需要等待");
            return R.error("请勿点击太快");
        }
        //获取用户id
        User user = (User) redisTemplate.opsForValue().get("token");
        String userId = user.getId();
        //设置用户id
        user.setId(userId);
        shoppingCart.setUserId(userId);

        //根据菜品/套餐 id获取购物车对象
        ShoppingCart shoppingCart1 = shoppingCartMapper.selectShoppingCartByDishId(shoppingCart);
        //判断该菜品/套餐是否为空
        if (shoppingCart1 != null) {
            //如果有了就把数量加一
            shoppingCart.setNumber(shoppingCart1.getNumber() + 1);
            // 修改数量
            shoppingCartMapper.updeteNumber(shoppingCart);
        } else {
            long timeMillis = System.currentTimeMillis();
            String id = timeMillis + "";
            //如果为空，直接加入菜品/套餐, 并把数量设置为1
            shoppingCart.setId(id);
            shoppingCart.setNumber(1);
            shoppingCartMapper.addShoppingCart(shoppingCart);
        }
        return R.success(shoppingCart);
    }

    /**
     * 购物车列表
     */
    public List<ShoppingCart> selectshoppingcart() {
        return shoppingCartMapper.selectshoppingcart();
    }

    /**
     * 清空购物车
     */
    public int cleanshoppingCart() {
        return shoppingCartMapper.cleanshoppingCart();
    }

    /**
     * 删除购物车商品
     */
    public R<Object> deleteshoppingCart(ShoppingCart shoppingCart) {
        //根据菜品、套餐id获取到购物车对象
        ShoppingCart sc = shoppingCartMapper.selectShoppingCartByDishId(shoppingCart);
        int num = sc.getNumber();
        //判断购物车菜品、套餐数量是否为空
        if (num >=1) {
            //如果购物车里有菜品、套餐就减一
            shoppingCart.setNumber(num - 1);
            //调用方法修改表数据
            shoppingCartMapper.updeteNumber(shoppingCart);
            //如果菜品数量小于1 直接删除
            if (num <= 1) {
                shoppingCartMapper.deleteshoppingCart(shoppingCart);
            }
        }
        return R.success(shoppingCart);
    }
}
